package com.zh.freechat.domain.user;

import com.zh.freechat.domain.user.entity.ChatUser;
import com.zh.freechat.domain.user.service.ChatUserService;
import com.zh.mycommon.value.RegexpConst;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;

import java.util.Set;

/**
 * 数据库获取用户信息
 *
 * @Author ZH
 * @Date 21:33 2020/4/18
 */
@Slf4j
@AllArgsConstructor
public class ChatUserDetailsService implements UserDetailsService {
    private final ChatUserService chatUserService;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        log.info("【有人Form登录 Web端】：username = {}", username);
        //数据库查询登录账号数据
        ChatUser userAtDb;
        if (username.matches(RegexpConst.REGEX_PHONE)) {
            userAtDb = chatUserService.findByPhone(username);
        } else if (username.matches(RegexpConst.REGEX_EMAIL)) {
            userAtDb = chatUserService.findByEmail(username);
        } else {
            userAtDb = chatUserService.findByUsername(username);
        }
        if (userAtDb == null) {
            throw new BadCredentialsException("账号或密码错误");
        }

        String role = userAtDb.getRole();
        log.debug("user role is {}", role);
        Set<SimpleGrantedAuthority> authorities = Set.of(new SimpleGrantedAuthority("ROLE_" + role));

        //生成Spring Security中登录用户的信息
        return new User(username, userAtDb.getPassword(), authorities);
    }

}
